package com.roc.web.action.terminal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTerActivateStatistics;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.SelfSupportStatisticsType;

@SuppressWarnings("serial")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/termSelfSupportActivateStatistics")
public class TermSelfSupportActivateStatisticsAction extends PaginationBaseAction {

	private Logger logger=LogManager.getLogger(TermSelfSupportActivateStatisticsAction.class);
	private TermSelfSupportActivateStatisticsSearchCondition searchCondition;
	private InputStream excelFile;

	@Autowired
	IPageService pagenitionService;
	@Autowired
	private IExcelService excelService;

	@Autowired 
	private IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	String effectAct;

	private List<TblTerActivateStatistics> terminalList=new ArrayList<TblTerActivateStatistics>();

	@Action(value="initPage",results={@Result(name="success",location="/pages/terminal/terminal_selfSupport_activate_statistics.jsp")
	,@Result(name="error",location="/error.jsp")})
	public String initTermSelfSupportActivateStatics() {
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			
			// 
			if(logingMerchant.getRoleType().equals(Role.MERCHANT.getCode())
					|| logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode()) ) {
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			
			String supId = String.valueOf(logingMerchant.getId());
			
			if(/*logingMerchant.getRoleType().equals(Role.SYSTEM.getCode())
					||*/ logingMerchant.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) 
					|| logingMerchant.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
					|| logingMerchant.getRoleType().equals(Role.WARE_HOUSE_LEAD)) {
				supId = Constant.SHOUDANSHIYEBU_ID;
			//	supId = Constant.ADMIN_ID;
			}
			// 登录账号为 代理商 或者 管理员,风控,仓库管理员,才有权限登录,注:代理商 中 只有收单事业部,分区和一级代理商有权限
			if(logingMerchant.getRoleType().equals(Role.AGENT.getCode()) 
					|| supId.equals(Constant.SHOUDANSHIYEBU_ID) ) {
				// 收单事业部,取收单事业部下各个区域id
				if( !supId.equals(Constant.SHOUDANSHIYEBU_ID) // 收单事业部/系统管理员/风控账号/仓库
						&& !String.valueOf(logingMerchant.getSuperiorId()).equals( Constant.SHOUDANSHIYEBU_ID ) // 区域
						&& !logingMerchant.getOneagentid().equals(String.valueOf(logingMerchant.getId())) ) {// 一级代理商
					addActionError("此登陆账号没有权限");
					return ERROR;
				}
			}

			searchCondition = new TermSelfSupportActivateStatisticsSearchCondition();
		
			// 查询所有一级代理商
		//	getRequest().setAttribute("oneAgentMap", map);
			org();
			
		} catch (Exception e) {
			addActionError("初始终端统计页面出错!!!");
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	@Action(value="queryTermSelfSupportActivateStatisticsList",results={@Result(name="success",location="/pages/terminal/terminal_selfSupport_activate_statistics.jsp")
	,@Result(name="error",location="/error.jsp")})
	public String queryTermSelfSupportActivateStatisticsList()
	{
		
		try {
			if (searchCondition == null) {
				searchCondition = (TermSelfSupportActivateStatisticsSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new TermSelfSupportActivateStatisticsSearchCondition();
				}
			}
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			
			// 
			if(logingMerchant.getRoleType().equals(Role.MERCHANT.getCode())
					|| logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode()) ) {
				addActionError("此登陆账号没有权限");
				return ERROR;
			}

			org();
			String supId = String.valueOf(logingMerchant.getId());
			
			// 如果登录账号为 系统管理员/风控主管/风控操作员/仓库
			if(/*logingMerchant.getRoleType().equals(Role.SYSTEM.getCode())
					||*/ logingMerchant.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) 
					|| logingMerchant.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
					|| logingMerchant.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
				supId = Constant.SHOUDANSHIYEBU_ID;
			//	supId = Constant.ADMIN_ID;
			}
			// 登录账号为 代理商 或者 管理员,风控,仓库管理员,才有权限登录,注:代理商 中 只有收单事业部,分区和一级代理商有权限
			if(logingMerchant.getRoleType().equals(Role.AGENT.getCode()) 
					|| supId.equals(Constant.SHOUDANSHIYEBU_ID) ) {
				// 收单事业部,取收单事业部下各个区域id
				if( !supId.equals(Constant.SHOUDANSHIYEBU_ID) // 收单事业部/系统管理员/风控账号/仓库
						&& !String.valueOf(logingMerchant.getSuperiorId()).equals( Constant.SHOUDANSHIYEBU_ID ) // 区域
						&& !logingMerchant.getOneagentid().equals(String.valueOf(logingMerchant.getId())) ) {// 一级代理商
					addActionError("此登陆账号没有权限");
					return ERROR;
				}
			}
			// 
			if( null == effectAct || "".equals(effectAct.trim()) ) {
				addActionError("统计类型不能为空");
				return ERROR;
			}
			// 
			searchCondition.setObj(supId);
			searchCondition.setEffectAct(effectAct);
			int rows = pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		//	getRequest().setAttribute("oneAgentMap", map);
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	@Action(value="excelTermSelfSupportActivateStatisticsList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/error.jsp") }) 
	public String  excelTermSelfSupportActivateStatisticsList() throws Exception{
		
			 Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

			 try {
				 if (searchCondition == null) {
					searchCondition = (TermSelfSupportActivateStatisticsSearchCondition) getSearchConditionFromSession();
					if (searchCondition == null) {
						searchCondition = new TermSelfSupportActivateStatisticsSearchCondition();
					}
				 }
				// 
				if(logingMerchant.getRoleType().equals(Role.MERCHANT.getCode())
						|| logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode()) ) {
					addActionError("此登陆账号没有权限");
					return ERROR;
				}

				String supId = String.valueOf(logingMerchant.getId());
					
				if(/*logingMerchant.getRoleType().equals(Role.SYSTEM.getCode())
						||*/ logingMerchant.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) 
						|| logingMerchant.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
						|| logingMerchant.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
						supId = Constant.SHOUDANSHIYEBU_ID;
					//supId = Constant.ADMIN_ID;
				}
				// 登录账号为 代理商 或者 管理员,风控,仓库管理员,才有权限登录,注:代理商 中 只有收单事业部,分区和一级代理商有权限
				if(logingMerchant.getRoleType().equals(Role.AGENT.getCode()) 
						|| supId.equals(Constant.SHOUDANSHIYEBU_ID) ) {
					// 收单事业部,取收单事业部下各个区域id
					if( !supId.equals(Constant.SHOUDANSHIYEBU_ID) // 收单事业部/系统管理员/风控账号/仓库
							&& !String.valueOf(logingMerchant.getSuperiorId()).equals( Constant.SHOUDANSHIYEBU_ID ) // 区域
							&& !logingMerchant.getOneagentid().equals(String.valueOf(logingMerchant.getId())) ) {// 一级代理商
						addActionError("此登陆账号没有权限");
						return ERROR;
					}
				}
				// 
				if( null == effectAct || "".equals(effectAct.trim()) ) {
					addActionError("统计类型不能为空");
					return ERROR;
				}
				searchCondition.setObj(supId);
				searchCondition.setEffectAct(effectAct);
				int rows = pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
					dealWithTheListSpecially(searchRsList);
				}
		//		Map<String, Map<String, String>> snStaMap = powerInfoService.querySnCount( Long.valueOf( supId ));
				SXSSFWorkbook work=excelService.exportTermSelfSupportActivateStaList(terminalList,null, effectAct , logingMerchant);

				ByteArrayOutputStream output = new ByteArrayOutputStream();  
				work.write(output);  
					   
				byte[] ba = output.toByteArray();  
				excelFile = new ByteArrayInputStream(ba);  
				output.flush();  
				output.close();  
					
		}catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	// 加载数据
	public void org() throws Exception{
		getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
		getRequest().setAttribute("selfSuppStatMap", SelfSupportStatisticsType.getAllEnumMap());
		
	}

	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		if(list!=null&&list.size()>0){
			
			Iterator<Object> iterator=list.iterator();
			while(iterator.hasNext())
			{				
				Object[] obj=(Object[]) iterator.next();
				TblTerActivateStatistics bean = new TblTerActivateStatistics();
				
				bean.setSerialNum(Constance.Null2EmptyTrim(obj[0])); // SN号

				String brandCode = Constance.Null2EmptyTrim(obj[1]);
				bean.setPosBrand( ConfigMerinfoUtil.getPosBRAND(brandCode) ); // 厂商
				bean.setBrandDate(Constance.Null2EmptyTrim(obj[2])); // 绑定日期
				bean.setTrnDate(Constance.Null2EmptyTrim(obj[3])); // 激活日期
		//		bean.setTrnAt(Constance.Null2EmptyTrim(obj[4])); // 交易总金额
				bean.setDtCreate(Constance.Null2EmptyTrim(obj[4])); // 创建时间
				bean.setDtLastmod(Constance.Null2EmptyTrim(obj[5])); // 更新时间
				bean.setAgentName(Constance.Null2EmptyTrim(obj[6]));// 代理商名称

				bean.setOneagentName(Constance.Null2EmptyTrim(obj[7])); // 一级代理商名称
				bean.setCompanyName(Constance.Null2EmptyTrim(obj[8])); // 所属分公司名称
				
				bean.setAgentId( Long.valueOf( Constance.Null2EmptyTrim(obj[9]) ) ); // 代理商Id

				bean.setMchntCd(Constance.Null2EmptyTrim(obj[10])); // 商户号
				bean.setTermId(Constance.Null2EmptyTrim(obj[11])); // 终端
			
				if ( !"".equals(Constance.Null2EmptyTrim(obj[12])) ) {

					bean.setOneagentId( Long.valueOf( Constance.Null2EmptyTrim(obj[12]) ) ); // 一级代理商id
				}

				terminalList.add(bean);
			}
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	public TermSelfSupportActivateStatisticsSearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(TermSelfSupportActivateStatisticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName="自营终端激活统计--"+Constance.formateDate();
		
		if ( Constant.STR_NUMBER_TWO .equals(effectAct) ) {
			excelName="自营终端有效商户激活统计--"+Constance.formateDate();
		}
		try {
			excelName = new String(excelName.getBytes(),"ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}
		 
		return  excelName;
	}
	public List<TblTerActivateStatistics> getTerminalList() {
		return terminalList;
	}
	public void setTerminalList(List<TblTerActivateStatistics> terminalList) {
		this.terminalList = terminalList;
	}
	public String getEffectAct() {
		return effectAct;
	}
	public void setEffectAct(String effectAct) {
		this.effectAct = effectAct;
	}
}
